import { defineStore } from 'pinia';
import { useWebsocketStore } from '@stores/websocketStore.ts';
import { HttpLogBean } from '@/beans/http_log_bean';
import { ref } from 'vue';

export const useHttpLogStore = defineStore('httpLog', () => {
  const logs = ref<HttpLogBean[]>([]); // Explicitly define the type of logs
  const websocketStore = useWebsocketStore();

  function handleHttpLog(data: string) {
    console.log('httpLogStore 收到消息', data);
    const httpLog = HttpLogBean.fromJson(JSON.parse(data));
    console.log('httpLogStore 解析消息', httpLog);
    httpLog.createTime = new Date();
    httpLog.responseTime =
      httpLog.response.createTime.getTime() - httpLog.request.createTime.getTime();
    console.log('httpLogStore 响应时间', httpLog.responseTime);
    logs.value.push(httpLog);
  }

  function unBindWebSocketListener() {
    websocketStore.unsubscribe('http_log', handleHttpLog);
  }

  function setupWebSocketListener() {
    websocketStore.subscribe('http_log', handleHttpLog);
  }

  function clearLogs() {
    logs.value = [];
  }

  return {
    // state
    logs,
    // actions
    handleHttpLog,
    unBindWebSocketListener,
    setupWebSocketListener,
    clearLogs,
  };
});
